package com.hl.ruoyizmhshop.controller;


import com.hl.ruoyizmhshop.domain.User;
import com.hl.ruoyizmhshop.service.IUserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user1")
public class LoginController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IUserService userService;

    @RequestMapping("/toLogin")
    public R toLogin(@RequestBody User  user) {
        // 1. 参数验证
    if (StringUtils.isAnyBlank(user.getUserAccount(), user.getUserPassword())) {
        throw new ServiceException("用户名或密码不能为空");
    }
    
    // 2. 查询用户
    User dbUser = userService.selectUserByAccount(user.getUserAccount());
    if (dbUser == null) {
        throw new ServiceException("用户名或密码错误");
    }
    
    // 3. 验证密码
    if (!dbUser.getUserPassword().equals(user.getUserPassword())) {
        throw new ServiceException("用户名或密码错误");
    }
    
    // 4. 验证用户状态
    if (dbUser.getUserStatus() != 1) {
        throw new ServiceException("用户已被禁用");
    }
    
    // 5. 转换为若依的LoginUser格式
    
    SysUser sysUser = new SysUser();
        sysUser.setUserId(dbUser.getUserId().longValue());
        sysUser.setUserName(dbUser.getUserAccount());
        LoginUser loginUser1 = new LoginUser();
        loginUser1.setUsername(dbUser.getUserAccount());
        loginUser1.setUserid(dbUser.getUserId().longValue());
        loginUser1.setSysUser(sysUser);
        //匹配登录成功，返回token给前端，同时保存用户信息到redis中
        return R.ok(tokenService.createToken(loginUser1));
    

    }
    @RequestMapping("/info")
    public R info(@RequestHeader(value = SecurityConstants.AUTHORIZATION_HEADER, required = false) String authorization){
        String token = SecurityUtils.replaceTokenPrefix(authorization);
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException("未登录或token缺失");
        }
        try {
            String userIdStr = JwtUtils.getUserId(token);
            Integer id = Integer.valueOf(userIdStr);
            User user = userService.selectUserByUserId(id);
            return R.ok(user);
        } catch (Exception e) {
            throw new ServiceException("无效的token");
        }
    }
}
